package com.totoro.tygeneratedragonblock;

import com.totoro.tygeneratedragonblock.commands.MainCommand;
import com.totoro.tygeneratedragonblock.commands.TestCommand;
import com.totoro.tygeneratedragonblock.constants.StaticSystemVarConst;
import com.totoro.tygeneratedragonblock.handler.GameProfileCacheHandler;
import com.totoro.tygeneratedragonblock.listener.BlockListener;
import com.totoro.tygeneratedragonblock.manager.*;
import com.totoro.tygeneratedragonblock.utils.ColorUtil;
import lombok.Getter;
import org.bukkit.World;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.world.WorldLoadEvent;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;

/* @version 0.1.0
 * @author Totoro
 * @date: ${DATE} - ${TIME}
 * @description Spigot-启动类
 */
public final class TyGenerateDragonBlock extends JavaPlugin  implements Listener {

    // 记录最后一个世界加载的时间
    private long lastWorldLoadTimestamp = 0;
    // 标记是否已完成初始化
    private boolean isInitialized = false;

    private static TyGenerateDragonBlock INSTANCE;

    @Getter
    private ConfigManager configManager;

    @Getter
    private LoggerManager loggerManager;

    @Getter
    private LanguageManager languageManager;

    @Getter
    private BlocksManager blocksManager;

    @Getter
    private GameProfileCacheHandler gameProfileCacheHandler;

    @Getter
    private ChunkMappingManager chunkMappingManager;

    @Getter
    private SpawnersManager spawnersManager;

    @Getter
    private RespawnTasksManager respawnTasksManager;

    @Override
    public void onEnable() {
        // 注册世界加载事件监听器
        getServer().getPluginManager().registerEvents(this, this);
        // 记录当前已加载的世界（服务器可能在插件加载前已加载了一些世界）
        for (World world : getServer().getWorlds()) {
            lastWorldLoadTimestamp = System.currentTimeMillis();
        }
        startWorldLoadCheckTask();
    }

    @EventHandler
    public void onWorldLoad(WorldLoadEvent event) {
        // 有新的世界加载时，更新最后加载时间戳
        lastWorldLoadTimestamp = System.currentTimeMillis();
        getLogger().info("检测到世界加载: " + event.getWorld().getName());
    }


    private void startWorldLoadCheckTask() {
        // 每2秒检查一次（40 ticks）
        new BukkitRunnable() {
            @Override
            public void run() {
                // 如果已经初始化完成，就取消任务
                if (isInitialized) {
                    cancel();
                    return;
                }

                // 计算距离最后一个世界加载已经过了多久
                long timeSinceLastLoad = System.currentTimeMillis() - lastWorldLoadTimestamp;

                // 如果3秒内没有新的世界加载，认为所有世界都已加载完成
                if (timeSinceLastLoad > 3000) {
                    initializePlugin();
                    isInitialized = true;
                    cancel();
                }
            }
        }.runTaskTimer(this, 0, 40); // 立即开始，每40ticks执行一次
    }

    private void initializePlugin() {
        getServer().getConsoleSender().sendMessage(StaticSystemVarConst.CONSOLE_PREFIX + ColorUtil.color("&e正在加载中..."));
        INSTANCE = this;
        configManager = new ConfigManager(this);
        loggerManager = new LoggerManager(this);
        languageManager = new LanguageManager(this);
        blocksManager = new BlocksManager(this);
        gameProfileCacheHandler = new GameProfileCacheHandler(this);
        chunkMappingManager = new ChunkMappingManager(this);
        spawnersManager = new SpawnersManager(this);
        respawnTasksManager = new RespawnTasksManager(this);

        if(null == getServer().getPluginManager().getPlugin("PlaceholderAPI")) {
            StaticSystemVarConst.dependentPlaceholderEnable = false;
            getServer().getConsoleSender().sendMessage(StaticSystemVarConst.CONSOLE_PREFIX +
                    ColorUtil.color("&c未找到依赖PlaceholderAPI，暂不启用PAPI变量解析"));
        }

        if(null == getServer().getPluginManager().getPlugin("DecentHolograms")) {
            StaticSystemVarConst.dependentDecentHologramsEnable = false;
            getServer().getConsoleSender().sendMessage(StaticSystemVarConst.CONSOLE_PREFIX +
                    ColorUtil.color("&c未找到依赖DecentHolograms，暂不启用方块名称显示"));
        } else {
            getServer().getConsoleSender().sendMessage(StaticSystemVarConst.CONSOLE_PREFIX +
                    ColorUtil.color("&e已找到依赖DecentHolograms，可以启用方块名称显示"));
        }

        MainCommand mainCommand = new MainCommand(this);
        getCommand("tgdb").setExecutor(mainCommand);
        getCommand("tgdb").setTabCompleter(mainCommand);
        getServer().getPluginManager().registerEvents(new BlockListener(this), this);

        getServer().getConsoleSender().sendMessage(StaticSystemVarConst.CONSOLE_PREFIX + ColorUtil.color("&e插件已经启动"));
    }

    @Override
    public void onDisable() {
        respawnTasksManager.cancelAllTask();
        getServer().getConsoleSender().sendMessage(StaticSystemVarConst.CONSOLE_PREFIX + ColorUtil.color("&e插件已经卸载"));
    }

    public static TyGenerateDragonBlock getInstance() {
        return INSTANCE;
    }
}
